//
//  RLPullDownMenu.m
//  RLPullDownMenu
//
//  Created by rylynn on 14-8-21.
//  Copyright (c) 2014年 rylynn. All rights reserved.
//
#import "RLPullDownMenu.h"

@interface RLPullDownMenu ()
@property (nonatomic, strong) UIButton *menuBtn;
@property (nonatomic, strong) UITableView *tableView;
@end

@implementation RLPullDownMenu
{
    UIView *_backGroundView;
    CAShapeLayer *_indicator;
    bool _show;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUp];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self setUp];
    }
    return self;
}

- (void)setUp {
    _indicatorHiden = NO;
    _selectItemEnable = YES;
    
    [self addSubview:self.menuBtn];
    
    // 创建背景
    _backGroundView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _backGroundView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.0];
    _backGroundView.opaque = NO;
    UIGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBackGround:)];
    [_backGroundView addGestureRecognizer:gesture];
    
    _show = NO;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    _menuBtn.frame = self.bounds;
    _tableView.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y + self.frame.size.height, self.frame.size.width, 0);
    
    if (!_indicatorHiden && !_indicator) {
        _indicator = [self creatIndicatorWithColor:mainRed andPosition:CGPointMake(self.frame.size.width - 20, self.frame.size.height / 2)];
        [self.menuBtn.layer addSublayer:_indicator];
    }
}
#pragma mark ------------------------------------------------------------
#pragma mark setter
- (void)setItemsArray:(NSArray <NSString *>*)itemsArray{
    _itemsArray = itemsArray;
    [self.menuBtn setTitle:itemsArray[0] forState:UIControlStateNormal];
}
#pragma mark ------------------------------------------------------------
#pragma mark lazyLoad
- (UIButton *)menuBtn {
    if (!_menuBtn) {
        _menuBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_menuBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        _menuBtn.titleLabel.font = [UIFont systemFontOfSize:18.0];
        [_menuBtn addTarget:self action:@selector(tapMenu) forControlEvents:UIControlEventTouchUpInside];
    }
    return _menuBtn;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [UITableView new];
        _tableView.rowHeight = 36;
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}



#pragma mark - tapEvent
- (void)tapMenu
{
    if (_show) {
        [self animateIdicator:_indicator background:_backGroundView tableView:self.tableView forward:NO complecte:^{
            _show = NO;
        }];
    } else {
        [self.tableView reloadData];
        [self animateIdicator:_indicator background:_backGroundView tableView:self.tableView forward:YES complecte:^{
            _show = YES;
        }];
    }
    
}

- (void)tapBackGround:(UITapGestureRecognizer *)paramSender
{
    [self animateIdicator:_indicator background:_backGroundView tableView:self.tableView forward:NO complecte:^{
        _show = NO;
    }];
}

#pragma mark - tableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self animateIdicator:_indicator background:_backGroundView tableView:self.tableView forward:NO complecte:^{
        _show = NO;
    }];
    if (_selectItemEnable) {
        [_menuBtn setTitle:_itemsArray[indexPath.row + 1] forState:UIControlStateNormal];
        _selectedIndex = indexPath.row + 1;
    }
    [self.delegate pullDownMenu:self didSelectRow:indexPath.row];
}


#pragma mark tableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_itemsArray count] - 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.textLabel.font = [UIFont systemFontOfSize:17.0];
    }
    
    [cell.textLabel setTextColor:[UIColor grayColor]];
    cell.textLabel.text = _itemsArray[indexPath.row + 1];
    return cell;
}

#pragma mark - animation
- (void)animateBackGroundView:(UIView *)view show:(BOOL)show complete:(void(^)())complete
{
    if (show) {
        [self.superview addSubview:view];
        [view.superview addSubview:self];

        [UIView animateWithDuration:0.2 animations:^{
            view.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.3];
        }];
    
    } else {
        [UIView animateWithDuration:0.2 animations:^{
            view.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.0];
        } completion:^(BOOL finished) {
            [view removeFromSuperview];
        }];
    }
    complete();
}

- (void)animateTableView:(UITableView *)tableView show:(BOOL)show complete:(void(^)())complete
{
    if (show) {
        tableView.frame = CGRectMake(0, self.frame.origin.y + self.frame.size.height, self.frame.size.width, 0);
        [self.superview addSubview:tableView];
        
        CGFloat tableViewHeight = ([tableView numberOfRowsInSection:0] > 5) ? (5 * tableView.rowHeight) : ([tableView numberOfRowsInSection:0] * tableView.rowHeight);
        
        [UIView animateWithDuration:0.2 animations:^{
            self.tableView.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y + self.frame.size.height, self.frame.size.width, tableViewHeight);
        }];

    } else {
        [UIView animateWithDuration:0.2 animations:^{
            self.tableView.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y + self.frame.size.height, self.frame.size.width, 0);
        } completion:^(BOOL finished) {
            [tableView removeFromSuperview];
        }];
    }
    complete();
}

- (void)animateIndicator:(CAShapeLayer *)indicator Forward:(BOOL)forward complete:(void(^)())complete
{
    if (indicator) {
        [CATransaction begin];
        [CATransaction setAnimationDuration:0.25];
        [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithControlPoints:0.4 :0.0 :0.2 :1.0]];
        
        CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation"];
        anim.values = forward ? @[ @0, @(M_PI) ] : @[ @(M_PI), @0 ];
        
        if (!anim.removedOnCompletion) {
            [indicator addAnimation:anim forKey:anim.keyPath];
        } else {
            [indicator addAnimation:anim andValue:anim.values.lastObject forKeyPath:anim.keyPath];
        }
        
        [CATransaction commit];
        
        indicator.fillColor = forward ? _tableView.tintColor.CGColor : mainRed.CGColor;
    }
    complete();
}

- (void)animateIdicator:(CAShapeLayer *)indicator background:(UIView *)background tableView:(UITableView *)tableView forward:(BOOL)forward complecte:(void(^)())complete{
    [self animateIndicator:indicator Forward:forward complete:^{
        [self animateBackGroundView:background show:forward complete:^{
            [self animateTableView:tableView show:forward complete:^{
            }];
        }];
    }];
    complete();
}

#pragma mark - drawing
- (CAShapeLayer *)creatIndicatorWithColor:(UIColor *)color andPosition:(CGPoint)point
{
    CAShapeLayer *layer = [CAShapeLayer new];
    
    UIBezierPath *path = [UIBezierPath new];
    [path moveToPoint:CGPointMake(0, 0)];
    [path addLineToPoint:CGPointMake(14, 0)];
    [path addLineToPoint:CGPointMake(7, 10)];
    [path closePath];
    
    layer.path = path.CGPath;
    layer.lineWidth = 1.0;
    layer.fillColor = color.CGColor;
    
    CGPathRef bound = CGPathCreateCopyByStrokingPath(layer.path, nil, layer.lineWidth, kCGLineCapButt, kCGLineJoinMiter, layer.miterLimit);
    layer.bounds = CGPathGetBoundingBox(bound);
    
    layer.position = point;
    
    return layer;
}
@end

#pragma mark - CALayer Category

@implementation CALayer (MXAddAnimationAndValue)

- (void)addAnimation:(CAAnimation *)anim andValue:(NSValue *)value forKeyPath:(NSString *)keyPath
{
    [self addAnimation:anim forKey:keyPath];
    [self setValue:value forKeyPath:keyPath];
}


@end
